<template>
  <div class="page-container">
    <div class="tree-table-panel flex-center-start">
      <div
        class="tree-panel"
        style="flex: 0 0 280px; margin-right: 20px; height: calc(100vh - 150px)"
      >
        <div class="tree-title">组织机构</div>
        <div class="mb-10 pd-10">
          <el-input
            size="small"
            prefix-icon="el-icon-search"
            placeholder="输入关键字进行过滤"
            v-model="deptFilterText"
          />
        </div>
        <div
          class="tree-content of-auto pd-10"
          style="height: calc(100vh - 350px)"
        >
          <div class="line-tree-panel">
            <el-tree
              v-loading="deptTreeLoading"
              ref="treeDept"
              class="line-tree"
              node-key="id"
              :data="deptTree"
              :default-expanded-keys="expandedKeysDept"
              :highlight-current="true"
              :filter-node-method="filterDeptNode"
              :props="deptProps"
              @node-click="handleDeptNodeClick"
            >
              <div slot-scope="{ node, data }" class="custom-tree-node">
                <div
                  :title="node.label"
                  style="
                    white-space: normal;
                    word-break: break-all;
                    height: 40px;
                    display: flex;
                    width: 100%;
                    align-items: center;
                  "
                  :style="{
                    'font-size':
                      node.level === 1
                        ? '16px'
                        : node.level === 2
                        ? '16px'
                        : '16px',
                    'font-weight': node.level === 1 ? 'bold' : '',
                  }"
                >
                  <span
                    v-if="
                      (node.level === 3 || node.level === 4) &&
                      node.childNodes.length === 0
                    "
                    class="ml-10 mr-10 w-5 h-5 radius-50 bg-999"
                  ></span>
                  <span
                    class="tree-icon"
                    :class="
                      node.childNodes.length === 0
                        ? 'level-4'
                        : node.level === 1
                        ? 'level-1'
                        : node.level === 2
                        ? 'level-2'
                        : node.level === 3
                        ? 'level-3'
                        : 'level-4'
                    "
                  />
                  <span style="line-height: 20px">{{ node.label }}</span>
                </div>
              </div>
            </el-tree>
          </div>
        </div>
      </div>
      <div
        class="flex-1 bg-white"
        style="
          height: calc(100vh - 150px);
          border: 1px solid #e4e4e4;
          border-radius: 4px;
        "
      >
        <div class="tree-table-panel">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="责任网格" name="first">
              <div class="flex-center-start" style="padding-right: 10px">
                <div
                  class="tree-panel"
                  style="
                    flex: 0 0 280px;
                    margin-right: 20px;
                    height: calc(100vh - 420px);
                    border: 0px;
                  "
                >
                  <div class="mb-10 pd-10">
                    <el-input
                      size="small"
                      prefix-icon="el-icon-search"
                      placeholder="输入关键字进行过滤"
                      v-model="filterText"
                    />
                  </div>
                  <div
                    class="tree-content of-auto pd-10"
                    style="height: calc(100vh - 360px)"
                  >
                    <div class="line-tree-panel">
                      <el-tree
                        v-loading="treeLoading"
                        ref="tree"
                        class="line-tree"
                        show-checkbox
                        node-key="id"
                        :data="treeData"
                        :default-expanded-keys="expandedKeysArea"
                        :default-checked-keys="girdList"
                        :props="defaultProps"
                        @check-change="handleCheckChange"
                        :check-strictly="true"
                        :filter-node-method="filterNode"
                      >
                        <div slot-scope="{ node }" class="custom-tree-node">
                          <div
                            :title="node.label"
                            style="
                              white-space: normal;
                              word-break: break-all;
                              height: 40px;
                              display: flex;
                              width: 100%;
                              align-items: center;
                            "
                            :style="{
                              'font-size':
                                node.level === 1
                                  ? '16px'
                                  : node.level === 2
                                  ? '16px'
                                  : '16px',
                              'font-weight': node.level === 1 ? 'bold' : '',
                            }"
                          >
                            <span
                              v-if="
                                (node.level === 3 || node.level === 4) &&
                                node.childNodes.length === 0
                              "
                              class="ml-10 mr-10 w-5 h-5 radius-50 bg-999"
                            ></span>
                            <span
                              class="tree-icon"
                              :class="
                                node.childNodes.length === 0
                                  ? 'area-4'
                                  : node.level === 1
                                  ? 'level-1'
                                  : node.level === 2
                                  ? 'area-2'
                                  : node.level === 3
                                  ? 'area-3'
                                  : 'area-4'
                              "
                            />
                            <span style="line-height: 20px">{{
                              node.label
                            }}</span>
                          </div>
                        </div>
                      </el-tree>
                    </div>
                  </div>
                </div>
                <div class="flex-1">
                  <div
                    id="all-map-d"
                    class="all-map-d"
                    style="height: calc(100vh - 365px)"
                  ></div>
                  <div class="flex-center-center" style="height: 80px">
                    <div class="map-btn blue w-150">
                      <i class="el-icon-edit fs-16 pr-10" /><span
                        >选择地图范围</span
                      >
                    </div>
                    <div
                      class="map-btn green w-150 mg-20"
                      @click="clearOverlays"
                    >
                      <i class="el-icon-brush fs-16 pr-10" /><span
                        >清空地图范围</span
                      >
                    </div>
                    <div class="map-btn yellow w-150 mg-20">
                      <i class="el-icon-refresh-right fs-16 pr-10" /><span
                        >刷新地图范围</span
                      >
                    </div>
                    <div class="map-btn yellow w-150" @click="saveGird">
                      <i class="el-icon-suitcase fs-16 pr-10" /><span
                        >保存地图范围</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="权责事项" name="second">
              <div class="page-container">
                <SearchPanel @change="handleSearchPanelChange">
                  <el-form
                    ref="queryForm"
                    class="query-more-form"
                    size="mini"
                    label-width="60px"
                    :model="query"
                  >
                    <el-row :gutter="20">

                       <el-col :span="3"
                        ><el-button
                          size="mini"
                          class="submit-btn"
                          @click="openThreeType"
                          >选择清单</el-button
                        ></el-col
                      >
                      <el-col :span="12"
                        ><el-form-item
                          label="权责清单"
                          prop="threeType"
                          class="threeType"
                          ><el-input
                            v-model="query.categoryCompleteName"
                            :disabled="true"
                            ref="threeType"
                            placeholder="请输入权责清单"
                            maxlength="255" /></el-form-item
                      ></el-col>
                     

                      <el-col :span="9" class="btn-col flex-between-center">
                        <el-button
                          size="mini"
                          class="search-btn"
                          @click="selectDeptCategory"
                          >查询</el-button
                        >
                        <div class="flex-end-center">
                          <div class="operation-btn yellow mr-10" @click="add">
                            <i class="el-icon-plus"></i>
                            <span>添加</span>
                          </div>
                          <div class="operation-btn red" @click="del">
                            <i class="el-icon-delete"></i>
                            <span>删除</span>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                  </el-form>
                </SearchPanel>

                <div class="table-container">
                  <div class="table-list-panel">
                    <el-table
                      v-loading="tableLoading"
                      :data="tableData"
                      :height="
                        isShow ? 'calc(100vh - 455px)' : 'calc(100vh - 375px)'
                      "
                      @selection-change="handleSelectionChange"
                    >
                      <el-table-column type="selection" width="55" />
                      <el-table-column
                        prop="categoryCompleteName"
                        label="权责清单全称"
                      />
                      <!-- <el-table-column
                        prop="categorySupName"
                        label="事件大类"
                      />
                      <el-table-column
                        prop="categorySubName"
                        label="事件小类"
                      /> -->
                    </el-table>
                  </div>
                  <div class="pagination-panel">
                    <Pagination
                      :total="query.total"
                      :page.sync="query.page"
                      :limit.sync="query.size"
                      @pagination="selectDeptCategory"
                    />
                  </div>
                </div>

              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <AddDeptCategoryDialog
      :dialog-type="dialogType"
      :dialog-visible="dialogVisible"
      :obj="obj"
      :dept-id="deptId"
      :dept-name="deptName"
      @flushPage="selectDeptCategory"
      @closeDialog="dialogVisible = false"
    />

     <!-- 三级分类弹窗 -->
    <ThreeTypeDialog
      :dialogVisible="ThreeTypeDialogVisible"
      @closeDialog="ThreeTypeDialogVisible = false"
      @threeTypeMsg='threeTypeMsg'
    />
  </div>
</template>

<script>
import SearchPanel from "@/components/SearchPanel";
import Pagination from "@/components/Pagination";
import ThreeTypeDialog from "@/views/casedeal/components/threeTypeDialog";
import AddDeptCategoryDialog from "./components/AddDeptCategoryDialog";
import { getTree, getOne } from "@/api/msg/grid";
import { addByDeptAndGrid, list } from "@/api/system/area";
import { industryArea } from "@/api/case";
import {
  roleDeptTreeselect,
  listDeptCategory,
  delDeptCategory,
} from "@/api/system/dept";
export default {
  name: "Planning",
  components: {
    SearchPanel,
    Pagination,
    ThreeTypeDialog,
    AddDeptCategoryDialog,
  },
  data() {
    return {
      activeName: "first",
      ThreeTypeDialogVisible: false,
      // 责任网格树
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
        // disabled: function (data, node) {
        //   return data.level !== 3;
        // },
      },
      deptFilterText: "",
      filterText: "",
      treeLoading: true,
      expandedKeysDept: [],
      expandedKeysArea: [],
      // 部门树
      deptTree: [],
      deptProps: {
        children: "children",
        label: "label",
      },
      deptId: null,
      deptName: "",
      deptTreeLoading: true,
      query: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        categoryDcaCode: "",
        categorySubCode: "",
        categorySupCode: "",
        deptId: "",
        categoryCompleteName:'',
      },
      tableLoading: false,
      tableData: [],
      multipleSelection: [],
      dialogType: "detail",
      dialogVisible: false,
      obj: {},
      centerMap: "",
      isShow: true,
      girdList: [],
      // 行业类型
      categoryDcaCodeArr: [],
      // 大类
      categorySupCodeArr: [],
      // 小类
      categorySubCodeArr: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    deptFilterText(val) {
      this.$refs.treeDept.filter(val);
    },
  },
  created() {
    this.init();
    this.getCategoryDcaCode();
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap();
    });
  },
  methods: {
    handleSearchPanelChange(flag) {
      this.isShow = flag;
    },

    // 打开三级分类的弹窗
    openThreeType(){
      this.ThreeTypeDialogVisible = true;
      this.$bus.$emit("remarks")
    },

    threeTypeMsg(data){
      console.log(data)
      this.query.categoryCompleteName=data.categoryCompleteName;
      this.query.categoryCode=data.code
    },

    // 获取行业领域
    getCategoryDcaCode() {
      industryArea({ parentId: 0 }).then((res) => {
        this.categoryDcaCodeArr = res.rows;
      });
    },
    // 获取大类
    getCategorySupCode(val) {
      industryArea({ parentId: val }).then((res) => {
        this.categorySupCodeArr = res.rows;
      });
    },
    // 获取小类
    getCategorySubCode(val) {
      industryArea({ parentId: val }).then((res) => {
        this.categorySubCodeArr = res.rows;
      });
    },
    // 初始化
    init() {
      this.treeLoading = true;
      getTree()
        .then((res) => {
          this.treeData = res.data;
          if (res.depts && res.depts.length > 0) {
            this.expandedKeysArea = res.depts.map((item) => item.id);
          }
          this.treeLoading = false;
        })
        .catch(() => {
          this.treeLoading = false;
        });
      roleDeptTreeselect(1)
        .then((res) => {
          this.deptTree = res.depts;
          if (res.depts && res.depts.length > 0) {
            this.expandedKeysDept = res.depts.map((item) => item.id);
          }
          this.deptTreeLoading = false;
        })
        .catch(() => {
          this.deptTreeLoading = false;
        });
    },
    // 选择组织机构
    handleDeptNodeClick(data) {
      this.query.deptId = data.id === 100 ? null : data.id;
      this.deptId = data.id;
      this.deptName = data.label;
      this.getGird(data.id);
      this.selectDeptCategory();
      this.clearOverlays();
    },
    // 查询网格
    getGird(id) {
      this.treeLoading = true;
      list({ deptId: id })
        .then((res) => {
          // 清空网格的选中
          this.$refs.tree.setCheckedKeys([]);
          // 初始化默认选中的key
          this.girdList = [];
          res.rows.forEach((item) => {
            this.girdList.push(item.areaId);
            this.showOverlays(item.areaId);
          });
          this.expandedKeysArea = this.girdList;
          this.treeLoading = false;
        })
        .catch(() => {
          this.treeLoading = false;
        });
    },
    // 选择网格
    handleCheckChange(data, checked) {
      this.clearOverlays();
      if (checked) {
        this.girdList.push(parseInt(data.id));
      } else {
        const index = this.girdList.indexOf(parseInt(data.id));
        if (index !== -1) {
          this.girdList.splice(index, 1);
        }
      }
      this.girdList.forEach((item) => {
        this.showOverlays(item);
      });
      // const index = this.girdList.indexOf(parseInt(data.id));
      // if (index !== -1) {
      //   this.girdList.splice(index, 1);
      // } else {
      //   this.girdList.push(parseInt(data.id));
      // }
    },
    // 保存网格
    saveGird() {
      if (this.deptId === 0 || this.deptId === null) {
        this.$message.warning("请先选择部门机构");
        return;
      }
      const girdList = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      if (girdList === null || girdList.length === 0) {
        this.$message.warning("请先选择网格");
        return;
      }
      this.treeLoading = true;
      var formDate = new FormData();
      formDate.append("deptId", this.deptId);
      formDate.append("girds", girdList.join(","));
      addByDeptAndGrid(formDate)
        .then((res) => {
          this.$message.success("添加成功");
          this.getGird(this.deptId);
          this.treeLoading = false;
        })
        .catch(() => {
          this.$message.error("添加失败");
          this.treeLoading = false;
        });
    },
    // 清除网格
    clearOverlays() {
      this.centerMap.clearOverlays();
    },
    // 在地图上显示网格
    showOverlays(id) {
      getOne(id).then((res) => {
        const ponit = [];
        const polygonArray = res.data.coords.split(";");
        const center = polygonArray[0].split(",");
        polygonArray.forEach((item) => {
          let polygon = item.split(",");
          ponit.push(new BMap.Point(polygon[0], polygon[1]));
        });
        // 绘制面
        var polygon = new BMap.Polygon(ponit, {
          strokeColor: "blue",
          strokeWeight: 2,
          strokeOpacity: 0.5,
        });
        this.centerMap.addOverlay(polygon);
        this.centerMap.centerAndZoom(new BMap.Point(center[0], center[1]), 15);
      });
    },
    // 切换tag
    handleClick(value) {
      if (value.name === "second") {
        this.selectDeptCategory();
      }
    },
    // 查询权责事项列表
    selectDeptCategory() {
      this.tableLoading = true;
      const query = JSON.parse(JSON.stringify(this.query));
      listDeptCategory(query)
        .then((res) => {
          this.tableLoading = false;
          this.tableData = res.rows;
          this.query.total = res.total;
          console.log(res.rows)
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    filterDeptNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 添加权责事项
    add() {
      if (this.deptId === null || this.deptId === 0) {
        this.$message.warning("请先选择部门");
        return;
      }
      this.dialogVisible = true;
      this.dialogType = "add";
      this.obj = null;
    },
    // 删除权责事项
    del() {
      const ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      delDeptCategory(ids)
        .then((res) => {
          this.$message.success("删除成功");
          this.selectDeptCategory();
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    },
    // 选择表格
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 初始化地图
    initMap() {
      this.centerMap = new BMap.Map("all-map-d");
      // 设置中心点坐标和地图级别
      this.centerMap.centerAndZoom("崇州市", 16);
      // 允许滚轮缩放
      this.centerMap.enableScrollWheelZoom(true);
    },
  },
};
</script>

<style lang='scss' scoped>
.all-map-d {
  width: 100%;
  top: 0px;
  left: 0;
}

/deep/ .threeType .el-form-item__label{
  width: 80px !important;
}
/deep/ .threeType .el-form-item__content{
  margin-left: 80px !important;
}
</style>
